package controllers;

import helpers.CountryHelper;
import helpers.HeaderHelper;
import helpers.ItuneXMLUrlHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import crawlers.CrawlerItuneXML;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;

import models.FeedType;
import models.Software;

public class TopCountry extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		
		response.setHeader("Cache-Control", "public, max-age=86400");
		response.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		
		response.setCharacterEncoding("UTF-8");
		//Set header page
		HeaderHelper headerHelper = new HeaderHelper();
		//Set variable
		ArrayList<Software> softwares = new ArrayList<Software>();
		
		//Obtain the session object, create a new session if doesn't exist
        HttpSession session = request.getSession(true);
		
        ItuneXMLUrlHelper urlHelper = new ItuneXMLUrlHelper();
		if (session.getAttribute("country") != null) {
			urlHelper.setCountry((String) session.getAttribute("country"));
		} else {
			if (CountryHelper.checkExistsCountry(request.getHeader("X-AppEngine-country"))) {
				urlHelper.setCountry(request.getHeader("X-AppEngine-country").toLowerCase());
			}
		}
		urlHelper.setGenreId("0");
		urlHelper.setLimit("10");
		
		//Set cache
        Cache cache=null;
        try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
		
        ArrayList<FeedType> types = urlHelper.getTypes();
        String cachename = "topapps_" + urlHelper.getCountry() + "_" + urlHelper.getType() + "_" + urlHelper.getLimit() + "_" + urlHelper.getGenreId();
        for (int i = 0 ; i < types.size(); i++) {
        	urlHelper.setType(types.get(i).getAlias());
        	cachename = "topapps_" + urlHelper.getCountry() + "_" + urlHelper.getType() + "_" + urlHelper.getLimit() + "_" + urlHelper.getGenreId();
        	if (cache.containsKey(cachename)) {
            	softwares = (ArrayList<Software>) cache.get(cachename);
            	System.out.println("softwares: cache print");
            } else {
            	softwares = (ArrayList<Software>) CrawlerItuneXML.getXML(urlHelper.getUrl());
            	if (softwares.size() > 0) {
            		cache.put(cachename, softwares);
            	}
    	        System.out.println("softwares: Data print");
            }
        	request.setAttribute("softwares" + Integer.toString(i), softwares);
        }
        
        //Set header
        headerHelper.setTitle("Top best " + urlHelper.getLimit() +  " free, paid for iphone, ipad in  country " + urlHelper.getCountry());
        headerHelper.setOgtitle("Top best " + urlHelper.getLimit() +  " free, paid for iphone, ipad in  country " + urlHelper.getCountry());
        
		/*SoftwareDebug.debug(softwares.get(0));*/
		request.setAttribute("headerHelper", headerHelper);
		request.setAttribute("country", urlHelper.getCountry());
		request.setAttribute("types", types);
		request.setAttribute("urlHelper", urlHelper);
		try {
			request.getRequestDispatcher("/pages/top_in_app.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
